import { type FC } from 'react';
import { View } from 'react-native';
import dayjs, { type Dayjs } from 'dayjs';
import { useSafeState, useMemoizedFn, useUpdateEffect } from 'ahooks';
import RNDateTimePicker, { type DateTimePickerEvent } from '@react-native-community/datetimepicker';
import DropdownConfirm from '../DropdownConfirm';
import { isIos } from '@/utils/helper';
import type { PickerProps } from './types';
import styles from './styles';

const Picker: FC<PickerProps> = (props) => {
  const { show, value } = props;
  const [date, setDate] = useSafeState<Dayjs>(value);
  const resetState = useMemoizedFn(() => setDate(value));
  const onConfirm = useMemoizedFn(() => props.onOk(date));

  const onChange = useMemoizedFn((evt: DateTimePickerEvent) => {
    const { nativeEvent, type } = evt;
    switch (type) {
      case 'dismissed': {
        props.onCancel();
        break;
      }
      case 'set': {
        setDate(dayjs(nativeEvent.timestamp));
        if (!isIos()) requestIdleCallback(onConfirm);
        break;
      }
    }
  });

  useUpdateEffect(resetState, [value]);

  const picker = (
    <RNDateTimePicker
      value={date.toDate()}
      display="spinner"
      onChange={onChange}
    />
  );

  if (!isIos()) {
    if (show) {
      return picker;
    } else {
      return null;
    }
  } else {
    return (
      <DropdownConfirm
        open={show}
        destroyOnClose
        duration={250}
        onOk={onConfirm}
        title="Date picker"
        onClose={props.onCancel}
        afterClose={resetState}
      >
        {() => (
          <View style={styles.picker}>
            {picker}
          </View>
        )}
      </DropdownConfirm>
    );
  }
}

export default Picker;